app.controller("nodeCtrl", ["$scope", "$http", "$filter", "$rootScope", "$stateParams", "$timeout", "$modal", "lodash",
function($scope, $http, $filter, $rootScope, $stateParams, $timeout, $modal, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $rootScope.initHeaderElements($scope.settings);
    $scope.breadcrumb.push('节点管理');

    $scope.settings.searchEle = {
        show: true, //显示查询框
        func: function (keyword) {
            searchNode(keyword);
        },
        blurFunc: function (keyword) {
            searchNode(keyword);
        }
    };

    $scope.info = {
        // 原始区域数据
        originNodeArray: [
            {"id": "1", "node": "176.0.0.1", "project": "PRO5", "purpose": "DEV",  "occupy": false, "startTime": 1528128000000, "endTime": 1528300800000, "status": "on", "isRent": true},
            {"id": "2", "node": "176.0.0.2", "project": "PRO2", "purpose": "QA",  "occupy": false, "startTime": 1528128000000, "endTime": 1528300800000, "status": "on", "isRent": true},
            {"id": "3", "node": "176.0.0.3", "project": "", "purpose": "",  "occupy": false, "startTime": 0, "endTime": 0, "status": "on", "isRent": false},
            {"id": "4", "node": "176.0.0.4", "project": "", "purpose": "",  "occupy": false, "startTime": 0, "endTime": 0, "status": "on", "isRent": false},
            {"id": "5", "node": "176.0.0.5", "project": "", "purpose": "",  "occupy": false, "startTime": 0, "endTime": 0, "status": "off", "isRent": true},
            {"id": "6", "node": "176.0.0.6", "project": "", "purpose": "",  "occupy": false, "startTime": 0, "endTime": 0, "status": "off", "isRent": false}
        ],
        // 租用项目
        originProjectArray: [
            {"id": "PRO1", "name": "upush1.0"},
            {"id": "PRO2", "name": "upush2.0"},
            {"id": "PRO3", "name": "ucloud1.0"},
            {"id": "PRO4", "name": "ucloud2.0"},
            {"id": "PRO5", "name": "Matrix一期"},
            {"id": "PRO6", "name": "Matrix二期"},
        ],
        // 租用目的
        originPurposeArray: [
            {"key": "DEV", "value": "开发"},
            {"key": "QA", "value": "测试"}
        ],
        nodeList: [],
    };

    //设置data-table
    $scope.options = {
        rowHeight: 40,
        headerHeight: 40,
        footerHeight: 50,
        columnMode: 'force',
        forceFillColumns: true,
        emptyMessage: '暂无数据！',
        columns: [
            { name: "服务", width: 100, prop: 'node'},
            { name: "租用项目", width: 100, prop: 'projectName'},
            { name: "租用目的", width: 80, prop: 'purposeName'},
            { name: "长期租用", width: 80,
                cellRenderer: function () {
                    return '<span>{{ $row.occupy ? "是" : "否" }}</span>';
                }
            },
            { name: "起租时间", width: 80, prop: 'startTime'},
            { name: "到期时间", width: 80, prop: 'endTime'},
            { name: "状态", width: 80,
                cellRenderer: function () {
                    return '<span>{{ $row.status == "on" ? "活跃" : "停止" }}</span>';
                }
            },
            {
                name: "操作",
                width: 100,
                cellRenderer: function () {
                    return '<a href="javascript:void(0);" ng-click="rentItem($row)" ng-if="!$row.isRent && $row.status == \'on\'">租用</a>' +
                           '<a href="javascript:void(0);" ng-click="recoveryItem($row)" ng-if="$row.isRent && $row.status == \'on\'">回收</a>' +
                           '<span ng-if="$row.status == \'off\'">需人工重启</span>';
                }
            }
        ],
    };

    setTableData();

    // 设置table数据
    function setTableData() {
        var filterNodeArray = new Array();
        angular.forEach($scope.info.originNodeArray, function(node) {
            // 设置租用项目
            node.projectName = node.project ? lodash.findWhere($scope.info.originProjectArray, {id: node.project}).name : "-";
            // 设置租用目的
            var filterPurposeItem = lodash.findWhere($scope.info.originPurposeArray, {key: node.purpose});
            node.purposeName = filterPurposeItem ? filterPurposeItem.value : "-";
            // 设置起租/到期时间
            node.startTime = node.startTime ? timestampToTime(node.startTime, true) : "-";
            node.endTime = node.endTime ? timestampToTime(node.endTime, true) : "-";
            filterNodeArray.push(node);
        });
        $scope.info.nodeList = filterNodeArray;
        $timeout(function() {            
            $scope.tableData = $scope.info.nodeList;
        }, 200);
    };

    // 查询节点数据
    function searchNode(keyword) {
        var searchNodeData = new Array();
        angular.forEach($scope.info.nodeList, function(node) {
            if(node.projectName == keyword || node.purposeName == keyword || node.startTime == keyword || node.endTime == keyword) {
                searchNodeData.push(node);
            }
        });
        $scope.tableData = searchNodeData.length ? searchNodeData : $scope.info.nodeList;
    };

    // 租用
    $scope.rentItem = function(row) {
        openModal("rent", row, $scope.info.originNodeArray, $scope.info.originProjectArray, $scope.info.originPurposeArray);
    }

    // 回收
    $scope.recoveryItem = function(row) {
        var confirm = {
            titleData: "提示",
            bodyData: "确定要回收该服务吗？"
        };
        $rootScope.confirmWindow(confirm, function (data) {
            if(data){
                var recoveryItem = lodash.findWhere($scope.info.nodeList, {id: row.id});
                recoveryItem.project = "";
                recoveryItem.projectName = "-";
                recoveryItem.purpose = "";
                recoveryItem.purposeName = "-";
                recoveryItem.occupy = false;
                recoveryItem.startTime = "-";
                recoveryItem.endTime = "-";
                recoveryItem.isRent = false;
                $rootScope.toasterSuccessInfo("回收成功！");
            }
        })
    }

    // 打开modal
    function openModal(type, row, nodeList, projectList, purposeList) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/nodeModal.html"),
            controller: "nodeModalCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                type: function () {
                    return type;
                },
                row: function () {
                    return row;
                },
                nodeList: function () {
                    return nodeList;
                },
                projectList: function () {
                    return projectList;
                },
                purposeList: function () {
                    return purposeList;
                }
            }
        });

        modalInstance.result.then(function (nodeItem) {
            ajaxFun(nodeItem, row);
        }, function (reason) {
            console.log("关闭modal");
        });
    };

    // 更新数据
    function ajaxFun(nodeItem, row) {
        var updateNodeItem = lodash.findWhere($scope.info.nodeList, {id: row.id});
        updateNodeItem.project = nodeItem.project;
        updateNodeItem.projectName = nodeItem.projectName;
        updateNodeItem.purpose = nodeItem.purpose;
        updateNodeItem.purposeName = nodeItem.purposeName;
        updateNodeItem.occupy = nodeItem.occupy;
        updateNodeItem.startTime = timestampToTime(new Date().getTime(), true);
        updateNodeItem.endTime = timestampToTime(nodeItem.endTime, true);
        updateNodeItem.isRent = true;
        $rootScope.toasterSuccessInfo("租用成功");
    }
}]);

app.controller("nodeModalCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "lodash", "type", "row", "nodeList", "projectList", "purposeList", function ($scope, $rootScope, $modalInstance, $http, lodash, type, row, nodeList, projectList, purposeList) {
    $scope.info = {
        nodeName: row.node,  // 服务名称
        projectList: [],     // 租用项目列表
        sltProjectItem: '',  // 选中的项目
        purposeList: [],     // 租用目的列表
        sltPurposeItem: '',  // 选中的项目
        endTime: 0,          // 到期时间(yyyy-MM-dd)
        overTime: 0,         // 到期时间(毫秒)
        occupy: false,       // 是否长期占用
    };

    setData();

    // 设置租用项目列表/租用目的列表格式
    function setData() {
        // 租用项目
        var filterProjectList = new Array();
        angular.forEach(projectList, function(project) {
            project.crtname = project.name;
            // 过滤已经存在的项目
            if(lodash.findIndex(nodeList, {project: project.id}) == -1) {
                filterProjectList.push(project);
            }
        });
        $scope.info.projectList = filterProjectList;
        // 租用目的
        angular.forEach(purposeList, function(purpose) {
            purpose.crtname = purpose.value;
        });
        $scope.info.purposeList = purposeList;
        // 结束时间
        var crtTime = new Date().getTime();
        $scope.info.endTime = timestampToTime(crtTime, true);
        $scope.info.overTime = crtTime;
    }

    // 是否长期占用
    $scope.changeCheckBox = function(type) {
        if(type) {
            $scope.info.endTime = "长期占用";
            $scope.info.overTime = 0;
        } else {
            var crtTime = new Date().getTime();
            $scope.info.endTime = timestampToTime(crtTime, true);
            $scope.info.overTime = crtTime;
        }
    };

    $scope.createClick = function () {
        if(!$scope.info.sltProjectItem) {
            $rootScope.toasterWarningInfo("租用项目不能为空！");
            return false;
        }
        if(!$scope.info.sltPurposeItem) {
            $rootScope.toasterWarningInfo("租用目的不能为空！");
            return false;
        }
        var nodeItem = {
            "project": $scope.info.sltProjectItem.id || "",
            "projectName": $scope.info.sltProjectItem.name || "",
            "purpose": $scope.info.sltPurposeItem.key || "",
            "purposeName": $scope.info.sltPurposeItem.value || "",
            "endTime": $scope.info.endTime,
            "occupy": $scope.info.occupy
        };
        $modalInstance.close(nodeItem);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);
